﻿/**
* CRL
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
//using System.Data;
using System.Text.RegularExpressions;
using System.Linq.Expressions;
using System.Diagnostics;
using CRL.LambdaQuery.Mapping;
using System.Collections.Concurrent;
using CRL.Core;
using CRL.DBAccess;
using System.Runtime.CompilerServices;

namespace CRL
{
    public class Base
    {
        //static internal bool UseEmitCreater = true;
        internal static Expression<Func<TModel, bool>> GetQueryIdExpression<TModel>(object id)
        {
            var type = typeof(TModel);
            var table = TypeCache.GetTable(type);
            if (table.PrimaryKey.PropertyType != id.GetType())
            {
                throw new Exception("参数类型与主键类型定义不一致");
            }
            var parameter = Expression.Parameter(type, "b");
            //创建常数 
            var constant = Expression.Constant(id);
            MemberExpression member = Expression.PropertyOrField(parameter, table.PrimaryKey.MemberName);
            var body = Expression.Equal(member, constant);
            //获取Lambda表达式
            var lambda = Expression.Lambda<Func<TModel, Boolean>>(body, parameter);
            //var pr = lambda.Compile();
            return lambda;
        }

        /// <summary>
        /// SQL语句转换为存储过程
        /// </summary>
        /// <param name="template"></param>
        /// <param name="dbContext"></param>
        /// <param name="sql"></param>
        /// <param name="procedureName"></param>
        /// <param name="templateParame"></param>
        /// <returns></returns>
        internal static string SqlToProcedure(string template, DbContextInner dbContext, string sql, string procedureName, Dictionary<string, string> templateParame = null)
        {
            var adpater = DBAdapter.DBAdapterBase.GetDBAdapterBase(dbContext);
            template = template.Trim();
            Regex r = new Regex(@"\@(\w+)", RegexOptions.IgnoreCase);//like @parame
            Match m;
            List<string> pars = new List<string>();
            for (m = r.Match(sql); m.Success; m = m.NextMatch())
            {
                string par = m.Groups[1].ToString();
                if (!pars.Contains(par))
                {
                    pars.Add(par);
                }
            }
            //string template = Properties.Resources.pageTemplate.Trim();
            sql = sql.Replace("'", "''");//单引号过滤
            template = template.Replace("{name}", procedureName);
            template = template.Replace("{sql}", sql);
            string parames = "";
            //构造参数
            if (dbContext.DBHelper.Params != null)
            {
                foreach (var p in dbContext.DBHelper.Params)
                {
                    string key = p.Key.Replace("@", "");
                    var t = p.Value.GetType();
                    var par = adpater.GetDBColumnType(t);
                    if (t == typeof(System.String))
                    {
                        par = string.Format(par, 500);
                    }
                    parames += adpater.SpParameFormat(key, par, false);
                }
            }
            if (dbContext.DBHelper.OutParams != null)
            {
                foreach (var p in dbContext.DBHelper.OutParams)
                {
                    string key = p.Key;
                    var t = p.Value.GetType();
                    var par = adpater.GetDBColumnType(t);
                    parames += adpater.SpParameFormat(key, par, true);
                }
            }
            if (parames.Length > 0)
            {
                parames = "(" + parames.Substring(0, parames.Length - 1) + ")";
            }
            template = template.Replace("{parame}", parames);
            if (templateParame != null)
            {
                foreach (var item in templateParame)
                {
                    var value = item.Value;
                    value = value.Replace("'", "''");//单引号过滤
                    template = template.Replace("{" + item.Key + "}", value);
                }
            }
            
            template = adpater.GetCreateSpScript(procedureName, template);
            return template;
        }
        /// <summary>
        /// 获取当前版本
        /// </summary>
        /// <returns></returns>
        public static string GetVersion()
        {
            var assembly = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            return assembly.Version.ToString();
        }
        //internal static string FormatFieldPrefix(DBAdapter.DBAdapterBase dBAdapter, Type type, string fieldName)
        //{
        //    return "{" + type.FullName + "}" + dBAdapter.KeyWordFormat(fieldName);
        //}
        #region callContext
        internal const string UseCRLContextFlagName = "__CRLContextFlagName";
        internal const string CRLContextName = "__TransDbContext";
        //internal const string AllDBExtendName = "__AllDBExtend";
        //internal const string SQLRunningtimeName = "__SQLRunningtime";
        internal const string UseTransactionScopeName = "__TransactionScopeName";
        internal const string ContextPathName = "__ContextPathName";
        #endregion
        internal static DataBaseArchitecture GetDataBaseArchitecture(DBType dbType)
        {
            if (dbType == DBType.MongoDB || dbType == DBType.ES)
            {
                return DataBaseArchitecture.NotRelation;
            }
            return DataBaseArchitecture.Relation;
        }
        internal static bool CheckIfAnonymousType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            return type.IsGenericType && type.Name.Contains("AnonymousType")
                && (type.Name.StartsWith("<>"))
                && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
        }
    }
}
